package com.xiaoqi.lesson.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.PathMatcher;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Author Rookie Coder
 * @Description 拦截器
 * @Date
 **/
@Slf4j
public class MyInterceptor implements HandlerInterceptor {

    // 注入开放性url
    @Value("${open.url}")
    private String userOpen;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("处理器方法执行之前调用拦截器");
        String requestURI = request.getRequestURI();
        log.info("拦截器拦截的地址："+requestURI);
        PathMatcher pathMatcher = new AntPathMatcher();
        boolean match = pathMatcher.match(requestURI, userOpen);
        if (match){

            log.info("拦截器放行的地址："+requestURI);
            return true;
        }
        else {
            // 判断用户是否登录
            String token = request.getHeader("token");
            // 用户已登陆
            if (StringUtils.isEmpty(token)){
                log.info("该用户已登陆，放行");
                return true;
            }
            // 用户未登录
            else {
                log.info("该地址不匹配"+requestURI);
                log.info("该用户未登陆，不放行");
                request.getRequestDispatcher("/user/noLogin/error").forward(request,response);
                return false;
            }
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        log.info("处理器方法执行之后调用拦截器");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("整个流程结束调用拦截器");
    }
}
